﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspose.Words;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using SXFramWork.Core;
using SXFramWork.Core.Extension;
using SXFramWork.Model;
using SXFramWork.Service;

namespace SXFramWork.API.Controllers.Admin
{
    /// <summary>
    /// 账户管理
    /// </summary>
    public class SysUserController : WebController
    {
        private readonly ISysUserService _userService;
        private readonly IWebHostEnvironment _hostEnvironment;
        public SysUserController(ISysUserService sysUserService,IWebHostEnvironment webHostEnvironment)
        {
            _hostEnvironment = webHostEnvironment;
            _userService = sysUserService;
        }
        /// <summary>
        /// 账户管理列表
        /// </summary>
        /// <param name="model">查询模型</param>
        /// <returns></returns>
        [HttpGet]
        [Menu("账户管理")]
        public async Task<IApiResult> List([FromQuery]UserQueryModel  model)
        {
            return await _userService.Query(model);
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="model">新增模型</param>
        /// <returns></returns>
        [HttpPost]
        [Power("新增",true)]
        public async Task<IApiResult> Add([FromBody]UserAddModel model)
        {
            return await _userService.Add(model);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Power("删除", true)]
        [Log]
        [AllowAnonymous]
        public async Task<IApiResult> Delete([FromQuery] string ids)
        {
            return await _userService.Delete(ids);
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Power("编辑",true)]
        [AllowAnonymous]
        public async Task<IApiResult> Update([FromBody]UserUpdateModel model)
        {
            return await _userService.Update(model);
        }
        /// <summary>
        /// 查询单个账户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [Power("查询单个账户",true)]
        [AllowAnonymous]
        public async Task<IApiResult> Get([FromQuery] string id)
        {
            return await _userService.GetById(id);
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Common]
        [AllowAnonymous]
        public async Task<IApiResult> EditPwd([FromBody]JObject parm)
        {
            return await _userService.EditPwd(parm.Value<string>("oldpwd"), parm.Value<string>("newpwd"));


        }
        /// <summary>
        /// pdf预览
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async  Task<IApiResult> GetPdf([FromQuery]string id)
        {
            //获取模板文件路径
            string fileName = Path.Combine(_hostEnvironment.WebRootPath, "files", "模板.docx");
            FileInfo info = new FileInfo(fileName);
            if (!info.Exists)
            {
                return ApiResult.NotOk("附件丢失");
            }
            LoadOptions opt = new LoadOptions();
            opt.Encoding = Encoding.UTF8;
            Aspose.Words.Document doc = new Aspose.Words.Document(fileName,opt);

            //处理sql得到数据
            List<object> param = new List<object>();
            param.Add(id);
            var sql_param = param.ToArray();
            var res= await _userService.GetUserInfo(id);
            SysUserEntity obj_data = res.Data; 

            //遍历普通域 插入
            DocumentBuilder builders = new DocumentBuilder(doc);
            string[] mailMerge = doc.MailMerge.GetFieldNames();
            foreach (var item in mailMerge)
            {
                var imageinfo = item.Split(':');
                if (imageinfo.Length < 2 || imageinfo[0] != "图片")
                {
                    if (obj_data.ContainProperty(item))
                    {
                        builders.MoveToMergeField(item);
                        var obj_data_val = obj_data.GetValueByProperty(item).To_String();
                        //解析
                        builders.Write(StringHelper.HtmlDecode(obj_data_val));

                    }
                    continue;
                }

                //处理图片
                var imgname = imageinfo[1];//图片名字
                var imgurl = obj_data.GetValueByProperty(imgname).To_String();//图片地址
                if (imgurl.Length < 1)
                    continue;
                double width = 0, height = 0;
                if (imageinfo.Length > 3)
                {
                    width = imageinfo[2].To_Double();//宽度
                    height = imageinfo[3].To_Double();//宽度
                }

                //合并域名和地址
                Uri url = new Uri(imgurl);
                //获取图片
                var bytes = HttpHelper.HttpWebRequestImage(url.ToString());
                if (bytes.Length < 1)
                {
                    builders.MoveToMergeField(imgname);
                    continue;
                }
                //将插入光标移到指定的图片域
                while (builders.MoveToMergeField(item))
                {
                    if (width != 0 || height != 0)
                        builders.InsertImage(bytes, width, height);
                    else
                        builders.InsertImage(bytes);
                }

            }
            var ss = doc.MailMerge.GetFieldNames();
            doc.MailMerge.DeleteFields();
            var docStream = new MemoryStream();
            doc.Save(docStream, SaveFormat.Pdf);
            Response.Clear();
            Response.ContentType = "application/pdf";
            await Response.Body.WriteAsync(docStream.GetBuffer(), 0, docStream.GetBuffer().Length);
            return ApiResult.Ok();
        }
        /// <summary>
        /// excel导出
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public IActionResult ExportExcel()
        {
            var dt = _userService.QueryUserDTable().Result;
            //if (dt == null)
            //throw new Exception("没有需要导出的数据！");
            string fileName =DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
            var ms = new MemoryStream();
            var workbook = ExcelHelper.ExportExcelHSSF(dt, "账号,角色,真实姓名,性别,电话,邮箱,地址");
            workbook.Write(ms);
            ms.Flush();
            ms.Seek(0, System.IO.SeekOrigin.Begin);
            var buffer = ms.GetBuffer();
            return File(buffer, "application/vnd.ms-excel", fileName);
        }
        /// <summary>
        /// Excel导入
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<IApiResult> ImportExcel([FromForm]IFormFile file)
        {
            return await _userService.ImportData(file);
        }


    }
}